<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="root"></div>

  <script src="../lib/react.js"></script>
  <script src="../lib/react-dom.js"></script>
  <script src="../lib/babel.js"></script>

  <script src="./data.js"></script>
  <script src="./format.js"></script>

  <script type="text/babel">
    class App extends React.Component {
      constructor() {
        super()

        this.state = {
          books: books
        }

      }    

      handleClick(index, count) {
        const newBooks = [...this.state.books]
        newBooks[index].count += count
        this.setState({
          books: newBooks
        })
      }

      removeItem(index) {
        const newBooks = [...this.state.books]
        newBooks.splice(index,1)
        this.setState({
          books: newBooks
        })
      }

      renderTable() {
        const { books } = this.state
        return (
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>书名</th>
                <th>价格</th>
                <th>出版日期</th>
                <th>购买数量</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {
                books.map((item, index) => {
                  return (
                    <tr key={index}>
                      <td>{ item.id }</td>
                      <td>{ item.name }</td>
                      <td>{ format(item.price) }</td>
                      <td>{ item.date }</td>
                      <td>
                        <button disabled={item.count <=1} onClick={() => this.handleClick(index,-1)}>-</button>
                        { item.count }
                        <button onClick={() => this.handleClick(index,1)}>+</button>
                      </td>
                      <td>
                        <button onClick={() => this.removeItem(index)}>删除</button>  
                      </td>
                    </tr>
                  )
                })
              }
            </tbody>
          </table>
        )
      }
      renderBlank() {
        return (<div>购物车数据为空</div>)
      }

      render() {
        const { books } = this.state
        let totalPrice = 0
        books.forEach((item, index) => {
          totalPrice += item.price*item.count
        })
        
        const showEl = books.length > 0 ? this.renderTable() : this.renderBlank()

        return (
          <div> 
            { showEl }
            <div>总价格: {format(totalPrice)}</div>
          </div>
        )
      }
    }


    const root = ReactDOM.createRoot(document.querySelector('#root'))
    root.render(<App />)
  </script>

  <style>
    table {
      border: collapse;
    }
    td, th {
      padding: 10px 16px;
      border: 1px solid #999;
    }
    button {
      margin: 0 10px;
    }
  </style>
</body>
</html>